package org.TCC_NOVO.server.Transferencia;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class ServletDownload extends HttpServlet{

    private Connection conn;
    private Statement stmt;

    private void Conectar(){
        try {
            /*Class.forName("org.firebirdsql.jdbc.FBDriver");
            conn = DriverManager.getConnection(
               "jdbc:firebirdsql:localhost/3050:E:/Pessoal/FURB/TCC_II/Banco_Dados/TCC.fdb",
               "sysdba",
               "masterkey");

            stmt = conn.createStatement();
            */
            
             //Abaixo é para fazer a conexão com o MySQL
             String url = "jdbc:mysql://localhost:3306/oas";
             //String url = "jdbc:mysql://localhost:3306/dbmy_81490";
             String user = "root";
             //String user = "DBMY_81490";
             String pass = "root";
             //String pass = "so93cvke";

             try {
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection(url,user,pass);
                stmt = conn.createStatement();
             }
                catch (ClassNotFoundException e){
                    System.out.println("Classe não encontrada");
             }

         } catch (Exception e) {
             System.out.println("Não foi possível conectar ao banco: " + e.getMessage());
         }
    }
    
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
        ResultSet rs = null;
        String fileName = "";
        boolean isMultiPart = FileUpload.isMultipartContent(request);
            if (isMultiPart) {
                Conectar();
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                try {
                    List items = upload.parseRequest(request);
                    Iterator iter = items.iterator();
                    while (iter.hasNext()) {
                        FileItem item = (FileItem) iter.next();                        
                        if (!item.isFormField()) {                            
                            String sID = item.getFieldName().split(",")[1];                            
                            String sTipo = item.getFieldName().split(",")[0];
                            String sSQL = "";
                            if (sTipo.equals("Tarefas"))
                                sSQL = "select nome_Arquivo from Atividade_Roteiro where ID = "+sID;
                            else//senão é unidade
                                sSQL = "select nome_Arquivo from Unidade where ID = "+sID;
                            try {
                                System.out.print(sSQL);
                                rs = stmt.executeQuery(sSQL);
                                while (rs.next()){
                                    fileName = rs.getString("nome_Arquivo");
                                }
                            }catch(SQLException ex) {
                                System.err.println("SQLException: " + ex.getMessage());
                            }

                            File file = new File(fileName);
                            if (file.exists() && file.isFile()) {
                                res.setContentType("application/octet-stream");
                                res.setContentLength((int)file.length());
                                res.setHeader("Content-disposition", "attachment;filename="+file.getName());
                                BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                                BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream());
                                byte b[] = new byte[1024]; //tamanho máximo permitido, podendo ser alterado
                                while (in.read(b) >= 0) {
                                    out.write(b);
                                }
                                in.close();
                                out.close();
                            } else {
                                throw new ServletException("Arquivo inválido ou corrompido.");
                            }
                        } } }
            catch (FileUploadException ex) { ex.printStackTrace();}
            catch (Exception ex) { ex.printStackTrace();}
         }
    }
}

